package com.boby.homecamera.adapter

import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.boby.homecamera.R
import com.boby.homecamera.constant.Constant
import com.boby.homecamera.db.VideoEventTable
import com.boby.homecamera.db.VideoTable
import com.boby.homecamera.net.Api
import com.boby.lib_common.BaseApplication
import com.boby.lib_common.extens.dp
import com.boby.lib_common.extens.setCornerRadius
import com.bumptech.glide.Glide
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.load.model.LazyHeaders
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.bumptech.glide.signature.ObjectKey
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale


class VideoEventAdapter(): RecyclerView.Adapter<VideoEventAdapter.VideoEventViewHolder>() {
    var data: MutableList<VideoEventTable.VideoEvent> = mutableListOf()
    private var itemClickListener: ((index:Int,item:VideoEventTable.VideoEvent)->Unit ?)? = null
    private var ip:String = ""
    private var token:String = ""
    private var httpPort = Constant.HTTP_SERVER_PORT
    fun setIp(ip:String,token:String,httpPort:Int ){
        this.ip = ip
        this.token = token
        this.httpPort = httpPort
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoEventViewHolder {
      val view =  LayoutInflater.from(parent.context).inflate(R.layout.item_video_event,parent,false)
        return VideoEventViewHolder(view)
    }

    override fun onBindViewHolder(holder: VideoEventViewHolder, position: Int) {
        val item = data[position]
        holder.msg_type.text = when(item.eventType){ //1，说话，2，婴儿哭声，3，移动侦测，4，人像
            1 -> "有人说话"
            2 -> "婴儿哭泣"
            3 -> "移动侦测"
            4 -> "有人出现"
            else -> "报警消息"
        }
        holder.msg_time.text= formatTimeHHmmss(item.startTime!!)
        holder.itemView.setOnClickListener {
            itemClickListener?.invoke(position,item)
        }


        val currentUrl = GlideUrl(
            "${Api.getRealUrl(ip,httpPort)}/video/getpic/?path=${item.capturePhoto}",
            LazyHeaders.Builder()
                .addHeader("Authorization", "Bearer ${token}")
                .build()
        )
        holder.iv_video_preview.tag = currentUrl
        holder.iv_video_preview.setCornerRadius(10f.dp())
        Glide.with(holder.iv_video_preview)
            .load(currentUrl)
//            .into(object : CustomTarget<Drawable>() {
//                override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
//                    // ✅ 加载完成后再判断是否仍是当前绑定的 item
//                    if (holder.iv_video_preview.tag == currentUrl) {
//                        holder.iv_video_preview.setImageDrawable(resource)
//                    }
//                }
//
//                override fun onLoadCleared(placeholder: Drawable?) {
//                    holder.iv_video_preview.setImageDrawable(placeholder)
//                }
//            })
            .into(holder.iv_video_preview)
    }
    override fun onViewRecycled(holder: VideoEventViewHolder) {
        super.onViewRecycled(holder)
        Glide.with(holder.iv_video_preview.context)
            .clear(holder.iv_video_preview)
    }

    override fun getItemCount(): Int {
      return  data.size
    }


    fun setItemClickListener(listener: (index:Int,item:VideoEventTable.VideoEvent) -> Unit ){
        this.itemClickListener = listener
    }

   public class VideoEventViewHolder(var itemView:View): ViewHolder(itemView){
        val msg_type = itemView.findViewById<TextView>(R.id.msg_type)
        val msg_time = itemView.findViewById<TextView>(R.id.msg_time)
        val iv_video_preview = itemView.findViewById<ImageView>(R.id.iv_video_preview)
    }
//
//    fun formatTimeHHmmss(timeValue: Long): String {
//        val hour = timeValue / 3600
//        val minute = (timeValue % 3600) / 60
//        val second = timeValue % 60
//        return String.format("%02d:%02d:%02d", hour, minute, second)
//    }
    fun formatTimeHHmmss(timestampMillis: Long): String {
        val sdf: SimpleDateFormat = SimpleDateFormat("HH:mm:ss:SSS", Locale.getDefault())
        val date: Date = Date(timestampMillis)
        return sdf.format(date)
    }
    fun formatTimemmss(timeValue: Long): String {
//        val hour = timeValue / 3600
        val minute = (timeValue % 3600) / 60
        val second = timeValue % 60
        return String.format("%02d'%02d", minute, second)
    }
}